import React, { Component } from "react"
import { messages } from "share/common"
import ReactDOM from 'react-dom'
import { Select, Icon, Popover } from 'antd'
import 'styles/components/chooser.scss'

class ChooserSelect extends Component {

  handleMouseEnter = () => {
    let temp = ReactDOM.findDOMNode(this).getElementsByTagName('li');
    Array.from(temp).forEach(item => {
      item.removeAttribute('title');
    });
  };

  handleFocus = () => {
    const { handleFocus } = this.props;
    this.refs.chooserBlur.focus();
    handleFocus();
  };

  clear = () => {
    const { clear } = this.props;
    clear();
  };

  render () {
    const { placeholder, disabled, newline, showClear, popoverParams, showNumber, value } = this.props;
    let popVisible = showNumber || !value.length ? {visible: false} : {};
    let className = this.classNames([
      'chooser',
      { 'number-only': showNumber },
      { 'chooser-disabled': disabled },
      { newline }
    ]);
    return (
      <div className={className}>
        <Popover
          placement="topLeft"
          content={value.map(v => v.label).join("，")}
          {...popVisible}
          {...popoverParams}
        >
          <Select
            style={{ width: '100%' }}
            value={value}
            mode="multiple"
            labelInValue
            placeholder={placeholder}
            onMouseEnter={this.handleMouseEnter}
            onFocus={this.handleFocus}
            dropdownStyle={{ display: 'none' }}
            maxTagPlaceholder={<div>{value.map(v => v.label).join(",")}</div>}
            disabled={disabled}
          />
          {value.length && !newline ? (
            <div className={`fake-value-list ${disabled ? 'disabled' : ''}`} onClick={disabled ? () => {} : this.handleFocus}>
              {value.map(v => v.label).join("，")}
            </div>) : ''
          }
        </Popover>
        {/*如果禁用了，就不要后面的清除icon*/}
        {
          (disabled || !showClear) ? "" : <Icon className="ant-select-selection__clear" type="close-circle" onClick={this.clear} style={value.length === 0 ? {opacity: 0} : {}}/>
        }
        <div className="chooser-number">
          {/*已选择 {value.length} 条*/}
          {messages('common.total.selected',{arg1: value.length===0?'0':value.length})/*已选 {arg1} 条*/}
        </div>
        <div>
          <input
            ref="chooserBlur"
            style={{ opacity: 0, position: 'fixed', width: 0, height: 0, zIndex: -1 }}
          />
        </div>
      </div>
    )
  }

  static defaultProps = {
    placeholder: messages('common.select')/*请选择*/,
    disabled: false,
    showNumber: false,
    newline: false,
    showClear: true,
    popoverParams: {}
  };

}

export default ChooserSelect
